package nobu.nakata.nfcfare.datamapper;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;

import net.sf.jsr107cache.Cache;
import nobu.nakata.nfcfare.table.ILongKeyEntity;


public class LongKeyDataMapper<T extends ILongKeyEntity> {
	private Cache cache;
	private PersistenceManager pm;
	private Class<T> klass;
	private String typeName;
	
	
	public LongKeyDataMapper(Cache cache, PersistenceManager pm, Class<T> klass) {
		 this.cache		= cache;
		 this.pm		= pm;
		 this.klass		= klass;		 
		 this.typeName	= klass.getSimpleName();
	}
	
	
	public T findByLongKey(Long key) {
		String cacheKey = makeCacheKey(key);
		T cached = (T) cache.get(cacheKey);
		if (cached != null)
			return cached;
		
		cached = loadFindByLongKey(key);
		cache.put(cacheKey, cached);
		return cached;
	}
	private T loadFindByLongKey(Long key) {
		try {
			T stored = pm.getObjectById(klass, key);
			return pm.detachCopy(stored);
		} catch(JDOObjectNotFoundException e) {
			return null;
		}
	}
	
	public T set(T item) {
		cache.remove(makeCacheKey(item.getKey()));
		return pm.detachCopy(pm.makePersistent(item));
	}
	
	
	private String makeCacheKey(Long key) {
		return typeName + ":" + key;
	}
}
